<?php

/*
 * gpa_demo
 * @filesource model_message.php
 * @author Meta Sanjaya
 */

class model_message extends Model {
    public function  __construct() {
        parent::__construct();
    }

    public function getUserMessages($uid) {
        $return = array();
        $rows = $this->db->query("SELECT * FROM #_users_messages WHERE to_user_id = '$uid' ORDER BY time_stamp DESC")->rows;

        foreach($rows as $r) {
            $mid = $r['message_id'];
            $rows = $this->db->query("SELECT subject, time_stamp FROM #_messages WHERE message_id = '$mid'")->rows;
            if(count($rows)) {
                $m_user = $this->getModel('user');
                $user = $m_user->getUserBy('user_id', $r['from_user_id']);
                //var_dump($user);
                $r['from'] = (count($user)?$user['username']:'Unknown');
                $r['time_stamp'] = $rows[0]['time_stamp'];
                $r['subject'] = $rows[0]['subject'];
                $return[] = $r;
            }
        }

        //var_dump($return);
        //exit;
        return $return;
    }

    public function getMessageUser($mid) {
        return $this->db->query("SELECT * FROM #_users_messages WHERE message_id = '$mid'")->rows;
    }

    public function getMessage($mid) {
        $this->db->query("UPDATE #_messages SET read = '1' WHERE message_id = '$mid'");
        return $this->db->query("SELECT * FROM #_messages WHERE message_id = '$mid'")->rows;
    }

    public function setMessage($from, $to, $subject, $content) {
        $subject = $this->db->escape(htmlspecialchars($subject));
        $content = $this->db->escape(htmlspecialchars($content));

        $this->db->query("INSERT INTO #_messages SET subject = '$subject', content = '$content'");
        $mid = $this->db->getInsertId();

        $this->db->query("INSERT INTO #_users_messages SET message_id = '$mid', from_user_id = '$from', to_user_id = '$to'");
    }
}

?>
